import { App } from 'vue'

function vueErrorHandler(err: unknown | Error, vm: any, info: string) {
  if (process.env.NODE_ENV === 'development') {
    console.error('>>>>>> 错误信息 >>>>>>')
    console.log(info)
    console.error('>>>>>> Vue 实例 >>>>>>')
    console.log(vm)
    console.error('>>>>>> Error >>>>>>')
    console.log(err)
  }
}

export function scriptErrorHandler(
  event: Event | string,
  source?: string,
  lineno?: number,
  colno?: number,
  error?: Error
) {
  if (event === 'Script error.' && !source) {
    return false
  }

  return true
}

function registerPromiseErrorHandler() {
  window.addEventListener('unhandledrejection', function (event) {}, true)
}

function registerResourceErrorHandler() {
  window.addEventListener('error', function (e: Event) {}, true)
}

export function setupErrorHandle(app: App) {
  app.config.errorHandler = vueErrorHandler

  window.onerror = scriptErrorHandler

  registerPromiseErrorHandler()

  registerResourceErrorHandler()
}
